package com.risetechnology.krystalkitchen1;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.database.SQLException;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Window;
import android.view.WindowManager;

import com.risetechnology.common.Shared;
import com.risetechnology.database.DbAdapter;
import com.risetechnology.database.DbHelper;
import com.risetechnology.utils.SmartSharedPreferrence;

public class ActivityCover extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Hide title bar
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// Set up full screen
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

		// Set up layout
		setContentView(R.layout.activity_cover);

		// Load font
		loadFont();

		// Create database
		initDatabase();

		// Go to introduction page 
		gotoIntroduction();
	}

	private void loadFont() {
		Shared.font = Typeface.createFromAsset(getAssets(), "comic_sans_ms.ttf");
	}


	/**
	 * Initial database
	 */
	private void initDatabase() {
		if(null != Shared.dbAdapter) return;
		
		DbAdapter dbAdapter = new DbAdapter(this);
		File db = getDatabasePath(DbHelper.DATABASE_NAME);
		if (db.exists()) {
			dbAdapter.open();
		} else {
			try {
				dbAdapter.close();
				dbAdapter.open(getAssets().open(DbHelper.DATABASE_NAME));
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				dbAdapter.open();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Shared.dbAdapter = dbAdapter;
	}


	/**
	 * Wait for some seconds, then go to introduction page
	 */
	private void gotoIntroduction() {
		CountDownTimer countDownTimer = new CountDownTimer(2000, 2000) {
			public void onTick(long millisUntilFinished) {
			}

			public void onFinish() {
				boolean isShowFirstIntro = SmartSharedPreferrence.getShowFirstIntro(ActivityCover.this);
				boolean isShowSecondIntro = SmartSharedPreferrence.getShowSecondIntro(ActivityCover.this);

				if (isShowFirstIntro) {
					Intent intent = new Intent(ActivityCover.this, ActivityFirstIntro.class);
					startActivity(intent);
					finish();
				} else if(isShowSecondIntro) {
					Intent intent = new Intent(ActivityCover.this, ActivitySecondIntro.class);
					startActivity(intent);
					finish();
				} else {
					Intent intent = new Intent(ActivityCover.this, TabsManager.class);
					startActivity(intent);
					finish();
				}
			}
		};
		countDownTimer.start();
	}
}
